package cn.hzc.fortess.system.controller;

import cn.hzc.fortess.core.shiro.ShiroKit;
import cn.hzc.fortess.system.entity.JwtUserToken;
import cn.hzc.fortess.system.service.JwtTokenService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;

@ApiIgnore
@Controller
@RequestMapping("/sam/oss")
public class CASController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CASController.class);

    @Autowired
    JwtTokenService jwtTokenService;

    @ApiIgnore
    @RequestMapping(method = RequestMethod.GET)
    public String ossTo(@RequestParam(value = "service") String serviceUrl) throws IOException {

        if (ShiroKit.getUser() == null || (!ShiroKit.isAuthenticated())) {
            return "/login.html";
        }
        String jwtToken = jwtTokenService.getJwtToken(super.getHttpServletRequest(), ShiroKit.getUser().getId());

        if (StringUtils.isBlank(jwtToken)) {
            log.warn("oss jwt token is null");
            return "/login.html";
        }
        if (serviceUrl.indexOf("?") > -1) {
            serviceUrl += ("&x-token=" + jwtToken);
        } else {
            serviceUrl += ("?x-token=" + jwtToken);

        }
        log.info("cas oss redirect:" + serviceUrl);
        getHttpServletResponse().sendRedirect(serviceUrl);
        return "/";
    }

    @Override
    protected String moduleName() {
        return "CAS-oss";
    }
}
